/*
 * @Author: 彭林
 * @Date: 2021-05-14 18:20:44
 * @LastEditTime: 2021-07-14 18:03:28
 * @LastEditors: 彭林
 * @Description:
 * @FilePath: /saas-app/app/service/class.go
 */
package service

import (
	"saas-app/app/dao"
	"saas-app/app/define"
	"saas-app/app/model"
	"unicode/utf8"

	"github.com/gogf/gf/database/gdb"
)

type ClassRepository interface {
	GetClassList(campus_id int, paging *define.PagingParams) (classList gdb.Result, total int, err error)
	GetClassSimpleList(campus_id uint) (classSimpleList gdb.Result, err error)
	UpdateClass(class_id uint, data map[string]interface{}) bool
	CreateClass(class *model.Classes) bool
	GetClassInfo(class_id int) gdb.Record
}

type classes struct{}

func ClassService() ClassRepository {
	return &classes{}
}

func (c classes) GetClassList(campus_id int, pagingParams *define.PagingParams) (classList gdb.Result, total int, err error) {

	var (
		page  = 1
		limit = 10
	)

	if pagingParams.Page > 0 && pagingParams.Limit > 0 {
		page = pagingParams.Page
		limit = pagingParams.Limit
	}

	db := dao.Classes.Where("campus_id = ?", campus_id)

	total, err = db.FindCount()

	if err != nil {
		return nil, total, err
	}

	classList, err = db.Offset((page - 1) * limit).Limit(limit).FindAll()

	return classList, total, err
}

func (c classes) GetClassSimpleList(campus_id uint) (classSimpleList gdb.Result, err error) {

	classSimpleList, err = dao.Classes.Where("campus_id = ?", campus_id).FindAll()

	return classSimpleList, err
}

func (c classes) UpdateClass(class_id uint, data map[string]interface{}) bool {

	if class_id <= 0 {
		panic("参数错误")
	}

	if data["class_name"] != nil && utf8.RuneCountInString(data["class_name"].(string)) > 20 {
		panic("参数错误 Class_name")
	}

	if data["capacity"] != nil && data["capacity"].(uint) > 99 {
		panic("参数错误 capacity")
	}

	if data["remark"] != nil && utf8.RuneCountInString(data["remark"].(string)) > 100 {
		panic("参数错误 remark")
	}

	if _, err := dao.Classes.Where("id = ?", class_id).Update(data); err != nil {
		panic(err)
	}
	return true
}

func (c classes) CreateClass(class *model.Classes) bool {

	_, err := dao.Classes.Save(class)

	if err != nil {
		panic(err)
	}

	return err == nil
}

func (c classes) GetClassInfo(class_id int) gdb.Record {

	classInfo, err := dao.Classes.Where("id = ?", class_id).FindOne()

	if classInfo == nil || err != nil {
		panic("信息不存在")
	}

	return classInfo
}
